package com.xiaocikuai.smallchunks.config.jwt;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {

    private static int timeday = 86400;

    //7天过期
    private static int delaytime = 30 * timeday;
    private static long expire = delaytime;
    private static String secret ="abcdfghiabcdfghiabcdfghiabcdfghi";
    //生成token
    public static String generateToken(String username){
        Date now = new Date();

        Date expiration = new Date(now.getTime()+ 1000 * expire);
        return Jwts.builder()
                .setHeaderParam("type","JWT")
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }


    public static Claims getClaimsByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            // Token 已过期，处理逻辑
            // 例如记录日志、返回错误信息等
            System.out.println("Token 已过期：" + e.getMessage());
            throw e;
        } catch (SignatureException | MalformedJwtException e) {
            // Token 签名验证失败或格式不正确，处理逻辑
            // 例如记录日志、返回错误信息等
            System.out.println("Token 解析失败：" + e.getMessage());
            throw e;
        } catch (JwtException e) {
            // 其他 JWT 异常，处理逻辑
            System.out.println("JWT 异常：" + e.getMessage());
            throw e;
        }
    }

}

